package com.shijiu.config;

import com.shijiu.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @Author xlj
 * @Date Created in  2023/4/9 20:12
 * @DESCRIPTION:
 * @Version V1.0
 */

@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
   @ExceptionHandler(value = MethodArgumentNotValidException.class)
   public Result handleValidException(MethodArgumentNotValidException e) {
      log.error("数据校验出现问题{}，异常类型{}", e.getMessage(), e.getClass());
      BindingResult bindingResult = e.getBindingResult();
      HashMap<String, Object> errorMap = new HashMap<>();
      bindingResult.getFieldErrors().forEach(item->{
         System.out.println(item);
         errorMap.put(item.getField(), item.getDefaultMessage());
      });
      return Result.fail(404,String.valueOf(errorMap));
   }
}